﻿@model ProductModel

@using Nop.Core.Domain.Catalog
@using Nop.Services.Catalog
@if (Model.Id > 0)
{
    if (Model.AvailableProductAttributes.Count > 0)
    {
        <div id="productattribute-edit">
            <ul>
                <li @Html.RenderSelectedTabIndex(0, 0)>
                    @T("Admin.Catalog.Products.ProductAttributes.Attributes")
                </li>
                <li>
                    @T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations")
                </li>
            </ul>
            <div>
                @TabAttributes()
            </div>
            <div>
                @TabAttributeCombinations()
            </div>
        </div>
        <script>
            $(document).ready(function() {
                $("#productattribute-edit").kendoTabStrip({
                    animation: {
                        open: {
                            effects: "fadeIn"
                        }
                    }
                });
            });
        </script>
    }
    else
    {
        @T("Admin.Catalog.Products.ProductAttributes.NoAttributesAvailable")
    }
}
else
{
    @T("Admin.Catalog.Products.ProductAttributes.SaveBeforeEdit")
}


@helper TabAttributes()
{
    <div id="productattributemappings-grid"></div>
    <script>
        $(document).ready(function() {
            $("#productattributemappings-grid").kendoGrid({
                dataSource: {
                    type: "json",
                    transport: {
                        read: {
                            url: "@Html.Raw(Url.Action("ProductAttributeMappingList", "Product", new { productId = Model.Id }))",
                            type: "POST",
                            dataType: "json"
                        },
                        create: {
                            url: "@Html.Raw(Url.Action("ProductAttributeMappingInsert", "Product", new { productId = Model.Id }))",
                            type: "POST",
                            dataType: "json"
                        },
                        update: {
                            url: "@Html.Raw(Url.Action("ProductAttributeMappingUpdate", "Product"))",
                            type: "POST",
                            dataType: "json"
                        },
                        destroy: {
                            url: "@Html.Raw(Url.Action("ProductAttributeMappingDelete", "Product"))",
                            type: "POST",
                            dataType: "json"
                        }
                    },
                    schema: {
                        data: "Data",
                        total: "Total",
                        errors: "Errors",
                        model: {
                            id: "Id",
                            fields: {
                                ProductAttribute: { editable: true, type: "string" },
                                ProductAttributeId: { editable: true, type: "number" },
                                TextPrompt: { editable: true, type: "string" },
                                IsRequired: { editable: true, type: "boolean" },
                                AttributeControlType: { editable: true, type: "string" },
                                AttributeControlTypeId: { editable: true, type: "number" },
                                //ProductId: { editable: false, type: "number" },
                                DisplayOrder: { editable: true, type: "number" },
                                ViewEditValuesUrl: { editable: false, type: "string" },
                                ViewEditValuesText: { editable: false, type: "string" },
                                ValidationRulesAllowed: { editable: false, type: "boolean" },
                                Id: { editable: false, type: "number" }
                            }
                        }
                    },
                    requestEnd: function(e) {
                        if (e.type == "create" || e.type == "update") {
                            this.read();
                        }
                    },
                    error: function(e) {
                        display_kendoui_grid_error(e);
                        // Cancel the changes
                        this.cancelChanges();
                    },
                    serverPaging: true,
                    serverFiltering: true,
                    serverSorting: true
                },
                pageable: {
                    refresh: true,
                    numeric: false,
                    previousNext: false,
                    info: false
                },
                toolbar: ["create"],
                edit: function(e) {
                    if (e.model.isNew()) {
                        //little hack here
                        //pre-select the first value of kendoui dropdownlist datasource
                        //for some reasons (maybe, bug) it always sends 0
                        //if no value has been selected (changed) in the dropdownlist
                        if (allProductAttributes.length > 0) {
                            e.model.ProductAttributeId = allProductAttributes[0].Id;
                        }
                        if (allAttributeControlTypes.length > 0) {
                            e.model.AttributeControlTypeId = allAttributeControlTypes[0].Id;
                        }
                    }
                },
                editable: {
                    confirmation: false,
                    mode: "inline"
                },
                scrollable: false,
                columns: [
                    {
                        field: "ProductAttributeId",
                        title: "@T("Admin.Catalog.Products.ProductAttributes.Attributes.Fields.Attribute")",
                        width: 250,
                        editor: productAttributeDropDownEditor,
                        template: "#:ProductAttribute#"
                    }, {
                        field: "TextPrompt",
                        title: "@T("Admin.Catalog.Products.ProductAttributes.Attributes.Fields.TextPrompt")",
                        width: 150
                    }, {
                        field: "IsRequired",
                        title: "@T("Admin.Catalog.Products.ProductAttributes.Attributes.Fields.IsRequired")",
                        width: 150,
                        headerAttributes: { style: "text-align:center" },
                        attributes: { style: "text-align:center" },
                        template: '<img src="@Url.Content("~/Administration/Content/images/")active-#=IsRequired#.gif" />'
                    },
                    {
                        field: "AttributeControlTypeId",
                        title: "@T("Admin.Catalog.Products.ProductAttributes.Attributes.Fields.AttributeControlType")",
                        width: 250,
                        editor: attributeControlTypeDropDownEditor,
                        template: "#:AttributeControlType#"
                    },
                    {
                        field: "DisplayOrder",
                        title: "@T("Admin.Catalog.Products.ProductAttributes.Attributes.Fields.DisplayOrder")",
                        width: 150,
                        //integer format
                        format: "{0:0}"
                    }, {
                        field: "ViewEditValuesUrl",
                        title: "@T("Admin.Catalog.Products.ProductAttributes.Attributes.Values")",
                        width: 150,
                        template: "# if(ViewEditValuesUrl !== null) {# <a href='#=ViewEditValuesUrl#\'>#:ViewEditValuesText#</a> #}  #"
                    },
                    {
                        field: "ValidationRulesAllowed",
                        title: "@T("Admin.Catalog.Products.ProductAttributes.Attributes.ValidationRules")",
                        width: 150,
                        template: "# if(ValidationRulesAllowed) {# <a href='javascript:OpenWindow(\"@Url.Content("~/Admin/Product/ProductAttributeValidationRulesPopup/")#=Id#?btnId=btnRefreshProductAttributes&formId=product-form\", 800, 300, true);'>@T("Admin.Catalog.Products.ProductAttributes.Attributes.ValidationRules.ViewLink")</a> #}  #"
                    },
                    {
                        command: [
                            {
                                name: "edit",
                                text: "@T("Admin.Common.Edit")"
                            }, {
                                name: "destroy",
                                text: "@T("Admin.Common.Delete")"
                            }
                        ],
                        width: 200
                    }
                ]
            });
        });

        //local datasource
        var allProductAttributes = [
            @for (int i = 0; i < Model.AvailableProductAttributes.Count; i++)
            {
                var productAttributeItem = Model.AvailableProductAttributes[i];
                <text>
            {
                Id: @(productAttributeItem.Value),
                Name: "@(Html.Raw(HttpUtility.JavaScriptStringEncode(productAttributeItem.Text)))"
            }
                </text>
                if (i != Model.AvailableProductAttributes.Count - 1)
                {
                    <text>,</text>
                }
            }
        ];

        var allAttributeControlTypes = [
            @{
                var allAttributeControlTypes = (from act in AttributeControlType.DropdownList.ToSelectList()
                    select new {Id = act.Value, Name = act.Text}).ToList();
            }
            @for (int i = 0; i < allAttributeControlTypes.Count; i++)
            {
                var attributeControlType = allAttributeControlTypes[i];
                <text>
            {
                Id: @(attributeControlType.Id),
                Name: "@(Html.Raw(HttpUtility.JavaScriptStringEncode(attributeControlType.Name)))"
            }
            </text>
                if (i != allAttributeControlTypes.Count - 1)
                {
                    <text>,</text>
                }
            }
        ];

        function productAttributeDropDownEditor(container, options) {
            $('<input required data-text-field="Name" data-value-field="Id" data-bind="value:ProductAttributeId"/>')
                .appendTo(container)
                .kendoDropDownList({
                    autoBind: false,
                    dataSource: allProductAttributes
                });
        }

        function attributeControlTypeDropDownEditor(container, options) {
            $('<input required data-text-field="Name" data-value-field="Id" data-bind="value:AttributeControlTypeId"/>')
                .appendTo(container)
                .kendoDropDownList({
                    autoBind: false,
                    dataSource: allAttributeControlTypes
                });
        }
    </script>
    <input type="submit" id="btnRefreshProductAttributes" style="display: none" />
    <script type="text/javascript">
        $(document).ready(function () {
            $('#btnRefreshProductAttributes').click(function () {
                //refresh grid
                var grid = $("#productattributemappings-grid").data('kendoGrid');
                grid.dataSource.read();
                
                //return false to don't reload a page
                return false;
            });
        });
    </script>
}
@helper TabAttributeCombinations()
{
    <p>
        <strong>@T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.Description")</strong>
    </p>
    <p>
        @T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.Description2")
    </p>
    <div>
        <div id="attributecombinations-grid"></div>

        <script>
            $(document).ready(function() {
                $("#attributecombinations-grid").kendoGrid({
                    dataSource: {
                        type: "json",
                        transport: {
                            read: {
                                url: "@Html.Raw(Url.Action("ProductAttributeCombinationList", "Product", new { productId = Model.Id }))",
                                type: "POST",
                                dataType: "json"
                            },
                            update: {
                                url: "@Html.Raw(Url.Action("ProductAttributeCombinationUpdate", "Product"))",
                                type: "POST",
                                dataType: "json"
                            },
                            destroy: {
                                url: "@Html.Raw(Url.Action("ProductAttributeCombinationDelete", "Product"))",
                                type: "POST",
                                dataType: "json"
                            }
                        },
                        schema: {
                            data: "Data",
                            total: "Total",
                            errors: "Errors",
                            model: {
                                id: "Id",
                                fields: {
                                    //ProductId: { editable: false, type: "number" },
                                    AttributesXml: { editable: false, type: "string" },
                                    Warnings: { editable: false, type: "string" },
                                    StockQuantity: { editable: true, type: "number" },
                                    AllowOutOfStockOrders: { editable: true, type: "boolean" },
                                    Sku: { editable: true, type: "string" },
                                    ManufacturerPartNumber: { editable: true, type: "string" },
                                    Gtin: { editable: true, type: "string" },
                                    OverriddenPrice: { editable: true, type: "number" },
                                    NotifyAdminForQuantityBelow: { editable: true, type: "number" },
                                    Id: { editable: false, type: "number" }
                                }
                            }
                        },
                        requestEnd: function(e) {
                            if (e.type == "update") {
                                this.read();
                            }
                        },
                        error: function(e) {
                            display_kendoui_grid_error(e);
                            // Cancel the changes
                            this.cancelChanges();
                        },
                        serverPaging: true,
                        serverFiltering: true,
                        serverSorting: true
                    },
                    pageable: {
                        refresh: true,
                        numeric: false,
                        previousNext: false,
                        info: false
                    },
                    editable: {
                        confirmation: false,
                        mode: "inline"
                    },
                    scrollable: false,
                    columns: [
                        {
                            field: "AttributesXml",
                            title: "@T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.Fields.Attributes")",
                            width: 400,
                            template: "#=AttributesXml#<br /> # if(Warnings !== null) {# <span style=\"color: red\">#=Warnings#</span> #}  #",
                            encoded: false
                        }, {
                            field: "StockQuantity",
                            title: "@T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.Fields.StockQuantity")",
                            width: 150,
                            //integer format
                            format: "{0:0}"
                        }, {
                            field: "AllowOutOfStockOrders",
                            title: "@T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.Fields.AllowOutOfStockOrders")",
                            width: 150,
                            headerAttributes: { style: "text-align:center" },
                            attributes: { style: "text-align:center" },
                            template: '<img src="@Url.Content("~/Administration/Content/images/")active-#=AllowOutOfStockOrders#.gif" />'
                        }, {
                            field: "Sku",
                            title: "@T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.Fields.Sku")",
                            width: 200
                        }, {
                            field: "ManufacturerPartNumber",
                            title: "@T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.Fields.ManufacturerPartNumber")",
                            width: 200
                        }, {
                            field: "Gtin",
                            title: "@T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.Fields.Gtin")",
                            width: 200
                        }, {
                            field: "OverriddenPrice",
                            title: "@T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.Fields.OverriddenPrice")",
                            width: 200,
                            editor: function (container, options) {
                                $('<input name="' + options.field + '"/>')
                                        .appendTo(container)
                                        .kendoNumericTextBox({
                                            format: "{0:n4}",
                                            decimals: 4
                                        });
                            }
                        }, {
                            field: "NotifyAdminForQuantityBelow",
                            title: "@T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.Fields.NotifyAdminForQuantityBelow")",
                            width: 150,
                            //integer format
                            format: "{0:0}"
                        }, {
                            command: [
                                {
                                    name: "edit",
                                    text: "@T("Admin.Common.Edit")"
                                }, {
                                    name: "destroy",
                                    text: "@T("Admin.Common.Delete")"
                                }
                            ],
                            width: 200
                        }
                    ]
                });
            });
        </script>
    </div>
    <div>
        <p>
            <input type="submit" id="btnAddNewCombination" value="@T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.AddNew")" onclick="javascript:OpenWindow('@(Url.Action("AddAttributeCombinationPopup", "Product", new { productId = Model.Id, btnId = "btnRefreshCombinations", formId = "product-form" }))', 800, 600, true); return false;" class="k-button" />
            <input type="button" id="btnGenerateAllCombinations" value="@T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.GenerateAll")" class="k-button" />
        </p>
        <input type="submit" id="btnRefreshCombinations" style="display: none" />
        <script type="text/javascript">
            $(document).ready(function () {
                //refresh button
                $('#btnRefreshCombinations').click(function () {
                    //refresh grid
                    var grid = $("#attributecombinations-grid").data('kendoGrid');
                    grid.dataSource.read();

                    //return false to don't reload a page
                    return false;
                });
                
                
                //generate combinations
                $('#btnGenerateAllCombinations').click(function () {
                    if (confirm('@T("Admin.Common.AreYouSure")')) {
                        $.ajax({
                            cache: false,
                            type: 'POST',
                            url: '@Url.Action("GenerateAllAttributeCombinations", "Product", new { productId = Model.Id })',
                            dataType: 'json',
                            success: function(data) {
                                //refresh grid
                                var grid = $("#attributecombinations-grid").data('kendoGrid');
                                grid.dataSource.read();
                            },
                            error: function(xhr, ajaxOptions, thrownError) {
                                alert('Error while generating attribute combinations');
                            }
                        });
                    }
                    return false;
                });
            });
        </script>
    </div>
}